package com.rtx.express.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestSender;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestSenderAddress;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemOrderInfo;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfo;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipient;
import com.pdd.pop.sdk.http.api.pop.request.PddWaybillGetRequest.ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipientAddress;
import com.pdd.pop.sdk.http.api.pop.response.PddWaybillGetResponse;
import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;

@RtxExpressApi(expressApiName = "拼多多")
@Service("快递接口PDD")
public class PDDExpressAPI implements IExpressService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	private static String  clientId ="f7c59777fcde431da4a387f13358f204";
	private static String  clientSecret ="10315322413fd86202f40f2a49277ba4a5c8fadf";
	private static String  userid ="2251799814527386";
	private static String  accesstoken ="4cbf15e431a34742bbacfe299805a196c7e99a53";


	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		PddWaybillGetResponse rsp = null;
		try {
			//获取配置信息
			mappingConfig(config);
			//获取单号&打印报文
			rsp = getExpress(bo);
			
			List<PddWaybillGetResponse.InnerPddWaybillGetResponseModulesItem> modules = rsp.getPddWaybillGetResponse().getModules();
			if(modules != null && modules.size() > 0){
				bo.setCallCreateOrderAPIResult("ok");
				
				PlExpressResult result = bo.getExpressResultFillSendAndReceiver();
				result.setResponseStr(bo.getCallCreateOrderAPIData());
				result.setExternorderkey(task.getExternorderkey());
				result.setWaybillNo(modules.get(0).getWaybillCode());
				result.setPrintData(modules.get(0).getPrintData());
				
				bo.setExpressResult(result);
			}else{
				bo.setMsg("订单-"+task.getExternorderkey()+"-获取拼多多快递单号失败：" + JSON.toJSONString(rsp));
			}
			
		} catch (Exception e) {
			log.error("订单-{}-获取拼多多快递单号失败：",task.getExternorderkey(),e);
			bo.setMsg("订单-"+task.getExternorderkey()+"-获取拼多多快递单号失败：" + e.getMessage()+JSON.toJSONString(rsp));
		}
	}
	
	private void mappingConfig(PlExpressApiConfig config) {
		if(!StringUtils.hasLength(config.getClientId())) {
			config.setClientId(clientId);
		}
		if(!StringUtils.hasLength(config.getClientSecret())) {
			config.setClientSecret(clientSecret);
		}
		if(!StringUtils.hasLength(config.getAccessToken())) {
			config.setAccessToken(accesstoken);
		}
	}
	

	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		
	}
	
	
	/**
	 * 获取快递单号
	 * @param Parameter
	 * @return
	 * @throws Exception
	 */
	private PddWaybillGetResponse getExpress(ExpressBO bo) throws Exception{
		PlExpressApiConfig config = bo.getExpressConfig();
		PopClient client = new PopHttpClient(config.getClientId(), config.getClientSecret());
		PddWaybillGetRequest request = mappingRequest(bo);
		String requestStr = JsonUtil.transferToJson(request);

		log.info("拼多多API快递面单接口请求报文:{}",requestStr);
		PddWaybillGetResponse response = client.syncInvoke(request, config.getAccessToken());
		log.info("拼多多API快递面单接口返回报文:{}",JsonUtil.transferToJson(response));
		return response;
	}
	
	//将wms参数映射到请求参数
	private PddWaybillGetRequest mappingRequest(ExpressBO bo) throws Exception{
		PlExpressApiConfig config = bo.getExpressConfig();
		PlExpressApi  task = bo.getExpressTask();
		String templateUrl = task.getTemplatesurl();
		
		PddWaybillGetRequest request = new PddWaybillGetRequest();

        ParamWaybillCloudPrintApplyNewRequest paramWaybillCloudPrintApplyNewRequest = new ParamWaybillCloudPrintApplyNewRequest();
        paramWaybillCloudPrintApplyNewRequest.setNeedEncrypt(false);

        ParamWaybillCloudPrintApplyNewRequestSender sender = new ParamWaybillCloudPrintApplyNewRequestSender();

        ParamWaybillCloudPrintApplyNewRequestSenderAddress address = new ParamWaybillCloudPrintApplyNewRequestSenderAddress();
        address.setCity(task.getSendCity());
        address.setDetail(task.getSendAddress());
        address.setDistrict(task.getSendCounty());
        address.setProvince(task.getSendProvince());
        sender.setAddress(address);
        sender.setMobile(task.getSendMobile());
        sender.setName(task.getSendName());
        sender.setPhone(task.getSendPhone());
        paramWaybillCloudPrintApplyNewRequest.setSender(sender);
        List<ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem> tradeOrderInfoDtos = new ArrayList<ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem>();

        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem item = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItem();
        item.setObjectId(task.getExternorderkey());
        if("SF".equals(config.getPlatformCarriercode())) {
        	item.setLogisticsServices("{ 'TIMED-DELIVERY': { 'value': '247' } }");
        }

        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemOrderInfo orderInfo = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemOrderInfo();
        orderInfo.setOrderChannelsType("PDD");
        List<String> tradeOrderList = new ArrayList<String>();
        tradeOrderList.add(task.getExternorderkey());
        orderInfo.setTradeOrderList(tradeOrderList);
        item.setOrderInfo(orderInfo);

        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfo packageInfo = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfo();
        packageInfo.setGoodsDescription("");
        packageInfo.setId("");
        List<ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem> items = new ArrayList<ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem>();

        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem item1 = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemPackageInfoItemsItem();
        item1.setCount(1);
        item1.setName("");
        items.add(item1);
        packageInfo.setItems(items);
        packageInfo.setPackagingDescription("");
        packageInfo.setTotalPackagesCount(1);
        packageInfo.setVolume(0L);
        packageInfo.setWeight(0L);
        item.setPackageInfo(packageInfo);

        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipient recipient = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipient();

        ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipientAddress address1 = new ParamWaybillCloudPrintApplyNewRequestTradeOrderInfoDtosItemRecipientAddress();
        address1.setCity(task.getReceiverCity());
        address1.setDetail(task.getReceiverAddress());
        address1.setDistrict(task.getReceiverCounty());
        address1.setProvince(task.getReceiverProvince());
        address1.setTown("");
        address1.setCountry("");
        recipient.setAddress(address1);
        recipient.setMobile(task.getReceiverMobile());
        recipient.setName(task.getReceiverName());
        recipient.setPhone(task.getReceiverPhone());
        item.setRecipient(recipient);
        item.setTemplateUrl(templateUrl);
        item.setUserId(Long.parseLong(Optional.ofNullable(config.getUserId()).orElse(userid)));
        tradeOrderInfoDtos.add(item);
        paramWaybillCloudPrintApplyNewRequest.setTradeOrderInfoDtos(tradeOrderInfoDtos);
        paramWaybillCloudPrintApplyNewRequest.setWpCode(task.getPlatformCarriercode());
        request.setParamWaybillCloudPrintApplyNewRequest(paramWaybillCloudPrintApplyNewRequest);
		return request;
	}
}
